package com.far.permissions.interceptor;

import com.far.permisions.context.DpContext;
import com.far.permisions.rule.base.RuleResultInvoker;
import com.far.permissions.support.SelectSqlActuator;
import com.far.permissions.support.BaseSqlActuator;
import com.far.permissions.support.UpdateSqlActuator;
import com.far.permissions.support.BuilderBoundSql;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.Properties;

@Slf4j
@Intercepts(
        {
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public class DataPermissionInterceptor implements Interceptor {

    private final RuleResultInvoker ruleResultInvoker;

    public DataPermissionInterceptor(RuleResultInvoker ruleResultInvoker) {
        this.ruleResultInvoker = ruleResultInvoker;
    }

    @Override
    public Object plugin(Object target) {
        // 使用默认的Mybatis提供的类生成代理对象
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(Properties properties) {
    }

    @Override
    public Object intercept(Invocation invocation) throws Exception {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        if (willDoRemake(ms.getId())) {
            args[0] = remakeMappedStatement(ms, sqlSource(ms));
        }
        return invocation.proceed();
    }

    /**
     * mybatis规范中，mapper不能使用重载，故认为全限定类名+方法名为唯一的statementId
     *
     * @param statementId
     * @return
     */
    private boolean willDoRemake(String statementId) {
        DpContext dpContext = DpContext.get();
        switch (dpContext.getStrategy()){
            case NONE:
                return false;
            case GLOBAL:
                return true;
            case DESIGNATED:
                return !dpContext.getExclusions().contains(statementId);
            default:
                return false;
        }
    }

    private BaseSqlActuator generateSqlActuator(BoundSql boundSql, SqlCommandType sqlCommandType) {
        BaseSqlActuator baseSqlActuator = null;
        switch (sqlCommandType) {
            case SELECT:
                baseSqlActuator = initSqlActuator(new SelectSqlActuator(boundSql,ruleResultInvoker));
                break;
            case UPDATE:
                baseSqlActuator = initSqlActuator(new UpdateSqlActuator(boundSql,ruleResultInvoker));
                break;
        }
        return baseSqlActuator;
    }

    private SqlSource sqlSource(MappedStatement ms){
        return parameterObject -> {
            BoundSql boundSql = ms.getBoundSql(parameterObject);
            BaseSqlActuator baseSqlActuator = null;
            try {
                baseSqlActuator = generateSqlActuator(boundSql, ms.getSqlCommandType()).execute();
                boundSql = BuilderBoundSql.builder().configuration(ms.getConfiguration())
                        .sql(baseSqlActuator.getNewSql())
                        .parameterMappings(baseSqlActuator.getParameterMappings())
                        .parameterObject(parameterObject)
                        .build();
            } catch (Exception e) {
                log.error("baseSqlActuator execute fail", e);
            }
            return boundSql;
        };
    }

    private BaseSqlActuator initSqlActuator(BaseSqlActuator baseSqlActuator) {
        try {
            baseSqlActuator.init();
        } catch (Exception e) {
            log.error("initSqlActuator fail", e);
        }
        return baseSqlActuator;
    }

    private MappedStatement remakeMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
                ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }
}
